package com.cfc.stage1;

/**
 * @description:
 * @author: yangxuan10
 * @create: 2024-04-15 14:42
 **/
public class MyHashMap1 {

    static class Node{
        Node next;
        int key;
        int value;
        Node(int _key,int _value){
            key = _key;
            value = _value;
        }
    }

    private Node[] nodes = new Node[10009];

    public void put(int key, int value) {
        int index = getIndex(key);
        Node loc = nodes[index],temp = loc;
        Node pre = null;
        if(loc != null){
            while(temp != null){
                if(temp.key == key){
                    temp.value = value;
                    return;
                }
                pre = temp;
                temp = temp.next;
            }
        }
        Node tail = new Node(key,value);
        if(pre != null){
            pre.next = tail;
        }else{
            nodes[index] = tail;
        }
    }

    public int get(int key) {
        int index = getIndex(key);
        Node loc = nodes[index];
        while(loc != null){
            if(loc.key == key){
                return loc.value;
            }
            loc = loc.next;
        }
        return -1;
    }

    public void remove(int key) {
        int index = getIndex(key);
        Node loc = nodes[index];
        Node pre = null;
        while(loc != null){
            if(loc.key == key){
                if(pre == null){
                    nodes[index] = loc.next;
                }else{
                    pre.next = loc.next;
                }
                return;
            }
            pre = loc;
            loc = loc.next;
        }
    }

    private int getIndex(int key){
        int hash = Integer.hashCode(key);
        hash ^= (hash >> 16);//尽量均匀分布
        return hash % nodes.length;
    }

}